package cn.gitee.worddemo.util;

import freemarker.template.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * word文档导出工具类
 */
@Component
public class WordUtil {
    final static Logger log = LoggerFactory.getLogger(WordUtil.class);

    //输出word文件路径目录
    @Value("${wordDemo.outDirectory}")
    private String basePath;
    //输出word文件路径目录
    @Value("${wordDemo.basePackagePath}")
    private String basePackagePath;

    public String getBasePath() {
        return basePath;
    }

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    public String getBasePackagePath() {
        return basePackagePath;
    }

    public void setBasePackagePath(String basePackagePath) {
        this.basePackagePath = basePackagePath;
    }

    public WordUtil(boolean init) {

    }

    public WordUtil() {
    }

    /**
     * 控制台打印通过模板生成的文件
     *
     * @param dataModel 数据模型
     * @param templateName 输出模版
     */
 /*   public String getContent(Map<String, Object> dataModel, String templateName) {

        try {

            StringWriter stringWriter = new StringWriter();

            getTemplate(templateName).process(dataModel, stringWriter);

            stringWriter.flush();

            String result = stringWriter.toString();

            stringWriter.close();

            return result;
        }
        catch (TemplateException e) {

            e.printStackTrace();
        }
        catch (IOException e) {

            e.printStackTrace();
        }

        return null;
    }*/


    /**
     * 创建通过模板生成的文件
     *
     * @param dataModel 数据模型
     * @param templateName 输出模版
     * @param filePath 输出文件路径   "/WebContent/WEB-INF/template"  下   /word/test.doc
     */
    public File create(Map<String, Object> dataModel, String templateName, String filePath) {

        try {
            filePath = basePath + filePath;
            File file = new File(filePath);

            if (!file.getParentFile().exists()) {

                file.getParentFile().mkdirs();
            }

            BufferedWriter bufWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"UTF-8"));

            // 创建配置实例
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            // 设置编码
            configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
            // ftl模板文件
            configuration.setClassForTemplateLoading(WordUtil.class, basePackagePath);

            configuration.getTemplate(templateName).process(dataModel, bufWrite);

            bufWrite.flush();
            bufWrite.close();

            return file;
        }
        catch (TemplateException e) {
            log.error("创建通过模板生成的文件1", e);
            e.printStackTrace();
        }
        catch (IOException e) {
            log.error("创建通过模板生成的文件2", e);
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据地址获得数据的字节流
     *
     * @param strUrl 网络连接地址
     * @return 图片Base64码
     */
    public String getImgBase64ByUrl(String strUrl) {

        try {

            // 建立 Http 链接
            HttpURLConnection conn = (HttpURLConnection) new URL(strUrl).openConnection();

            // 5秒响应超时
            conn.setConnectTimeout(5 * 1000);
            conn.setDoInput(true);

            // 判断http请求是否正常响应请求数据，如果正常获取图片 Base64 码
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                // 获取图片输入流
                InputStream inStream = conn.getInputStream();

                // 用于存储图片输出流
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();

                // 定义缓存流，用于存储图片输出流
                byte[] buffer = new byte[1024];

                int len = 0;

                // 图片输出流循环写入
                while ((len = inStream.read(buffer)) != -1) {

                    outStream.write(buffer, 0, len);
                }

                // 图片输出流转字节流
                byte[] btImg = outStream.toByteArray();

                inStream.close();
                outStream.flush();
                outStream.close();

                Base64.Encoder encoder = Base64.getEncoder();
                return encoder.encodeToString(btImg);
            }
        }
        catch (Exception e) {

            e.printStackTrace();
        }

        return null;
    }


    //根据绝对路径获得图片的base64码
    public static String getImageBase(String src) throws Exception {
        if (src == null || src == "") {
            return "";
        }
        File file = new File(src);
        if (!file.exists()) {
            return "";
        }
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }

}
